import { ListRawState } from "../../views/home"

export interface CartRawState extends ListRawState {
  count: number
  state: boolean
}

const initState = {
  cartList: [] as CartRawState[]
}

const cartReducer = (state = initState, action: any) => {
  const { type, payload } = action;

  // 购物+
  if (type === 'addCar') {
    // 查询商品
    const item = state.cartList.find(v => v.id === payload.id);
    // 判断商品是否存在  存在数量++
    if (item) item.count++;
    // 不存在 推入新数据
    else state.cartList.push(payload);
    return {
      ...state,
      cartList: [...state.cartList]
    }
  }

  // 购物-
  if (type === 'subCar') {
    // 查询商品
    const item = state.cartList.find(v => v.id === payload.id);
    // 判断商品是否存在  存在数量++
    if (item) item.count--;
    return {
      ...state,
      cartList: [...state.cartList]
    }
  }

  // 单选
  if (type === 'oneState') {
    // 查询商品
    const item = state.cartList.find(v => v.id === payload.id);
    // 判断商品是否存在  存在
    if (item) item.state = !item.state

    return {
      ...state,
      cartList: [...state.cartList]
    }
  }

  // 全选
  if (type === 'allState') {
    state.cartList.forEach(v => {
      // 修改所有单选状态
      v.state = payload
    })
    return {
      ...state,
      cartList: [...state.cartList]
    }
  }

  // 删除
  if (type === 'delCar') {
    // 通过 ID删除
    const newList = state.cartList.filter(v => v.id !== payload.id)
    return {
      ...state,
      cartList: newList
    }
  }

  return state
}

export default cartReducer